package com.itheima.reggie.common;

import com.itheima.reggie.exception.CustomerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;

//全局异常捕获器
@RestControllerAdvice
@Slf4j
public class GloablExceptionHandler  {
    /**
     * 异常处理方法
     */
    //只针对添加新员工时,表字段已存在抛出的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerSqlException(SQLIntegrityConstraintViolationException ex) {

        System.out.println("有异常");
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String username = message.split(" ")[2];
            return R.error(username + "已存在");
        }
        return R.error("未知错误");
    }


    /**
     * 自定义异常处理方法
     */
    //抛出的异常为自定义异常,代表删除该分类的操作不合法
    @ExceptionHandler(CustomerException.class)
    public R<String> handlerSqlException(CustomerException ex) {
        return R.error(ex.getMessage());
    }
}
